#include "app_mqtt.h"
#include <MQTTClient.h>
#include <stdio.h>
#include "log.h"
#include <string.h>
 


static MQTTClient client;
static MQTTClient_connectOptions  options=  MQTTClient_connectOptions_initializer ;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;    

int  (*app_mqtt_recieve_callback)(char *);

static void app_mqtt_connectionLost(void* context, char* cause)
{
    log_error( " mqtt  connectionLost :cause :%s" ,cause);
}

/**
 * @brief 消息达到回调
 */
int app_mqtt_messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message)
{   //1 把消息内容提取出来 , 用内部的回调函数调用（实质调用的内容 由外部注册）
    if(app_mqtt_recieve_callback==NULL)
    {
        return 0;
    }
    int ret= app_mqtt_recieve_callback( message->payload) ;
    if(ret==0)
    {
        return 1;
    }else
    {
        return 0;
    }

}
/**
 *  @brief mqtt消息发送成功后回调
 *  ps: 只有QoS1和QoS2才有效
 */
void app_mqtt_deliveryComplete(void* context, MQTTClient_deliveryToken dt)
{
    log_info(" 消息发送成功 ");
}

/**
 * @brief 初始化mqtt客户端
 * 
 *  1  create 创建客户端
2  设置回调
3  连接 
4  订阅

 */
int  app_mqtt_init()
{
    // *  1  create 创建客户端
    int ret=  MQTTClient_create(&client, MQTT_BROKER_URI, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if(ret==-1)
    {
        log_error(" MQTTClient_create error");
    }
    // 2  设置回调
    MQTTClient_setCallbacks(client, NULL, app_mqtt_connectionLost, app_mqtt_messageArrived, app_mqtt_deliveryComplete);
    // 3  连接 
    ret= MQTTClient_connect(client, &options);
    if(ret ==-1)
    {
        perror(" MQTTClient_connect error");
        return -1;
    }
    // 4  订阅
    ret=MQTTClient_subscribe(client, MQTT_SUBSCRIBE_TOPIC, MQTT_QOS);
    if(ret==-1)
    {
        log_error(" MQTTClient_subscribe error");
        return -1;
    }
    return 0;

}

 

/**
 * @brief 发布mqtt消息
 */
int app_mqtt_publish( char *payload)
{
    pubmsg.payload=payload;
    pubmsg.payloadlen=strlen(payload);
    MQTTClient_publishMessage(client,MQTT_PUBLISH_TOPIC,&pubmsg,NULL);
    return 0;

}


/**
 * @brief 注册接收数据的回调函数
 */
int app_mqtt_register_recv_callback( int  (*callback)(char *))
{
    app_mqtt_recieve_callback=callback;
    return 0;
}


/**
 * @brief 销毁mqtt
 */
void app_mqtt_destroy()
{
    MQTTClient_disconnect(client,1000);
    MQTTClient_destroy(&client);
}